package cs236369.hw5;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet({"/UpdateTeam", "/UpdateTeam/*"})
public class updateTeam extends HttpServlet {
	private static final long serialVersionUID = 6812849187221387464L;
	private HttpSession session;
	private PrintWriter out;
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession();
		try {
			out = response.getWriter();
		} catch (IOException e) {
			response.setStatus(400);
			return;
		}
		// if no session- redirect to welcome page
		if(session == null || session.getAttribute("userName") == null) {
			response.sendRedirect(request.getContextPath() + InitListener.welcomePage);
			return;
		}
		try {
			String command = request.getParameter("command");
			if(command == null) {
				updateDetails(request);
			} else if(command.equals("delete")) {
				deleteTeam(request);
			} else if(command.equals("leave")) {
				leaveTeam(request);
			} else if(command.equals("join")) {
				joinTeam(request);
			} else {
				System.err.println("Command " + command + " is unknown");
				throw new RescueMeException("unknown command", "Command " + command + " is unknown");
			}
			response.setStatus(200);
			out.print("Team updated successfully");
		} catch (RescueMeException e) {
			response.setStatus(400);
			out.print(e.getMessage());
		}
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private void updateDetails(HttpServletRequest request) throws RescueMeException {
		// create skills array
		ArrayList<Skill> skills = new ArrayList<Skill>();	// to add skills dynamically
		Skill[] sa = new Skill[0];	// a dummy array for creating skills arrays

		Map<String, String[]> params = request.getParameterMap();
		for (String parameter : params.keySet()) {
		    if(parameter.contains("newSkillId")) {
		    	try {
			    	int skillID = Integer.parseInt(params.get(parameter)[0]);
			    	if(skillID > -1 ) { skills.add(new Skill(skillID, "", true)); }
		    	} catch (NumberFormatException e) {
		    		throw new RescueMeException("illegal parameter", "Skill ID is incorrect");
				} 
		    }
		}
		
		String numberString = request.getParameter("capacity");
		int capacity, limit;
		try {
			if(numberString == null || Integer.parseInt(numberString) < 0) {
				throw new RescueMeException("illegal parameter", "Capacity is not a positive integer");
			} else {
				capacity = Integer.parseInt(numberString);
			}
		} catch (NumberFormatException e) {
			throw new RescueMeException("illegal parameter", "Capacity is not a positive integer");
		}
		numberString = request.getParameter("limit");
		try {
			if(numberString == null || Integer.parseInt(numberString) < 1) {
				throw new RescueMeException("illegal parameter", "Limit is not a positive integer");
			} else {
				limit = Integer.parseInt(numberString);
			}
		} catch (NumberFormatException e) {
			throw new RescueMeException("illegal parameter", "Capacity is not a positive integer");
		}
		Team team = new Team(getTeamId(request), (String)session.getAttribute("userName"), null, null, capacity,
				request.getParameter("content"), 0, 0, skills.toArray(sa), limit);
		DBConnection.updateTeam(team);
	}
	
	private void deleteTeam(HttpServletRequest request) throws RescueMeException {
		int teamId = getTeamId(request);
		Team team = DBConnection.getTeam(teamId);
		if(!team.getOwner().equals(session.getAttribute("userName"))) {
			throw new RescueMeException("unauthorized", "This user is unauthorized to delete team id " + teamId);
		}
		DBConnection.delPost(teamId, 1);
	}
	
	private void joinTeam(HttpServletRequest request) throws RescueMeException {
		int teamId = getTeamId(request);
		Team team = DBConnection.getTeam(teamId);
		String username = (String) session.getAttribute("userName");
		if(team.isMember(username)) {
			throw new RescueMeException("illegal operation", "User " + username + " is alredy a member in team id " + teamId);
		}
		DBConnection.addUserToTeam(teamId, username);
	}
	
	private void leaveTeam(HttpServletRequest request) throws RescueMeException {
		int teamId = getTeamId(request);
		Team team = DBConnection.getTeam(teamId);
		String username = (String) session.getAttribute("userName");
		if(!team.isMember(username)) {
			throw new RescueMeException("illegal operation", "User " + username + " is not a member of team id " + teamId);
		}
		DBConnection.removeUserFromTeame(teamId, username);
	}
	
	public static int getTeamId(HttpServletRequest request) throws RescueMeException {
		String numberString = request.getParameter("teamId");
		try { return Integer.parseInt(numberString); }
		catch (NumberFormatException e) {
			throw new RescueMeException("illegal parameter", "team id is incorrect");
		}
	}
}
